var winston = require('winston');
var mysql = require('mysql');
var ejs = require('ejs');
var Promise = require("bluebird");
var fs = require("fs");
var path = require('path');
var API_KEY = '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';

var sendgrid  = require('sendgrid')(API_KEY);

var emailContent = fs.readFileSync(path.join(__dirname, "..", "templates/email/2015046.html")).toString();

module.exports = function(pool, req, res, next){
	var email = req.query.email;
	//var emailRE = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;
	var emailRE = /^(?:[-\w])+(?:\.[-\w]+)*@(?:[-\w])+(?:(?:\.[-\w]+)+)$/;
	var eventId = '2015046';
	if(!emailRE.test(email)){
		res.status(400).send('bad email format');
		return
	}
	var emailObject = new sendgrid.Email({
	  to:       email,
	  from:     'rginthecity@we-product.com',
	  fromname: 'rginthecity',
	  replyto: 	'no-reply@we-product.com',
	  subject:  '罗兰·加洛斯在城市：法网红土魅袭帝都',
	  html:     emailContent
	});
	var isSuccess = 1;
	sendgrid.send(emailObject, function(error, json) {
	    if(error){
	        winston.error(error);
			isSuccess = 0;												
	    }else{
	        winston.info('Message sent: ' + json.message);
	    }
	    res.send({msg:'ok'});
	    pool.getConnection(function(err, connection){
			if(err){
				winston.error('DB connection error: ' + err);
				res.status(500).send('DB connection error: ' + err);
			}

			var queryString = 'INSERT INTO email_sent (email, name, event_id, uri_map, is_success, timestamp) VALUES (?, ?, ?, ?, ?, ?)';
											
			var params = [email, '', eventId, 'nomap',  isSuccess, String.from(Date.now())];
			connection.query(mysql.format(queryString, params), function(err){
				if(err){
					winston.error('DB query error: ' + err);
				}else{
					connection.release();
				}
			});
		});
	});
		
}